﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using Common.BaseLibrary.Authorization;
using Common.BaseLibrary.Logger;
using Common.BaseLibrary.Utils;
using DepartmentWork.Migrator.Data;
using DepartmentWork.Model;
using DepartmentWork.Platform.Controllers;

namespace DepartmentWork.Platform.Areas.ProjectManageArea.Controllers
{
    public class ProjectController : BaseController
    {
        //
        // GET: /ProjectManageArea/Project/

        public ActionResult Index(string flag = "", string info = "")
        {

            #region 设置分页

            var pageSizeExecute = this.Request["pageSizeExecute"] == null ? 10 : int.Parse(Request["pageSizeExecute"]);
            var pageIndexExecute = this.Request["pageIndexExecute"] == null ? 1 : int.Parse(Request["pageIndexExecute"]);

            ViewData["pageIndexExecute"] = pageIndexExecute;
            ViewData["pageSizeExecute"] = pageSizeExecute;

            var pageSize = this.Request["pageSizeFinish"] == null ? 10 : int.Parse(Request["pageSizeFinish"]);
            var pageIndex = this.Request["pageIndexFinish"] == null ? 1 : int.Parse(Request["pageIndexFinish"]);

            ViewData["pageIndexFinish"] = pageIndex;
            ViewData["pageSizeFinish"] = pageSize;

            #endregion

            #region 校验身份

            #region 原版

            //string[] pathArr = Request.Path.Split('/');
            //Guid userGuid = new Guid(CurrentUser.UserID);
            //USER_INFO user = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();
            //USER_TEAMSAPCE userTeam = userTeamsapceRepository.GetModel(r => r.USER_ID == user.USER_ID).FirstOrDefault();
            //ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == userTeam.ROLE_ID).FirstOrDefault();
            //List<MENU_ROLE> menuRole = menuRoleRepository.GetModel(r => r.ROLE_ID == role.ROLE_ID).ToList();
            //for (int i = 0; i < menuRole.Count(); i++)
            //{
            //    int menuId = menuRole[i].MENU_ID;
            //    MENU menu = menuRepository.GetModel(r => r.MENU_ID == menuId).FirstOrDefault();
            //    if (menu.AREA_NAME == pathArr[2] && menu.CONTROLLER_NAME == pathArr[3])
            //    {
            //        ViewBag.IsAdmin = true;
            //        break;
            //    }
            //}

            #endregion

            #region 改版后

            //1 、 获取当前用户所在角色
            //2. 获取该角色 所具有的 所有 权限
            //3. 确认该角色是否具有该权限
            Guid userGuid = new Guid(CurrentUser.UserID);
            USER_INFO user = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();
            USER_TEAMSAPCE userTeam = userTeamsapceRepository.GetModel(r => r.USER_ID == user.USER_ID).FirstOrDefault();
            ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == userTeam.ROLE_ID).FirstOrDefault();
            List<AUTHORITY_ROLE> authRoleList =
                authorityRoleRepository.GetModel(r => r.ROLE_ID == role.ROLE_ID).ToList();



            for (int i = 0; i < authRoleList.Count; i++)
            {
                bool result = false;
                result =
                    empAuthorityRepository.GetModel(r => r.AUTHORITY_ID == authRoleList[i].AUTHORITY_ID)
                        .FirstOrDefault()
                        .AUTHORITY_TITLE.Contains("项目管理新增操作");
                if (result == true)
                {
                    ViewBag.IsAdmin = true;
                    break;

                }
            }

            #endregion

            if (ViewBag.IsAdmin == true)
            {
                #region 获取该团队空间下的全部人员

                //TempData["UserList"] = userRepository.GetModel().ToList();

                List<UserInfoViewModel> userList = new List<UserInfoViewModel>();
                List<USER_TEAMSAPCE> userTeams = userTeamsapceRepository.GetModel(r => r.TEAMSPACE_ID == userTeam.TEAMSPACE_ID).ToList();
                userList.AddRange((from item in userTeams
                                   select new UserInfoViewModel()
                                   {
                                       UserId = item.USER_ID
                                   }).ToList());
                for (int i = 0; i < userList.Count(); i++)
                {
                    var id = userList[i].UserId;
                    userList[i].UserName =
                        userRepository.GetModel(r => r.USER_ID == id).FirstOrDefault().DISPLAY_NAME;
                }
                TempData["UserList"] = userList;

                #endregion
            }

            #endregion

            ProjectManagementViewModel model = new ProjectManagementViewModel();

            IList<PROJECT_MANAGEMENT> projectManagementsExecutingList = projectManagementRepository.GetModel(r => r.PROJECT_MANAGEMENT_STATUS == 0).OrderByDescending(r => r.PROJECT_MANAGEMENT_CREATETIME).ToList();
            IList<PROJECT_MANAGEMENT> projectManagementsFinishList = projectManagementRepository.GetModel(r => r.PROJECT_MANAGEMENT_STATUS == 1).OrderByDescending(r=>r.PROJECT_MANAGEMENT_CREATETIME).ToList();
            model.ExecuteProjectList = new DataSet();
            model.ExecuteProjectList = DataSetHelp.Instance.ToDataSet(projectManagementsExecutingList);
            model.FinishProjectList = DataSetHelp.Instance.ToDataSet(projectManagementsFinishList);

            ViewData["totalExecute"] = model.ExecuteProjectList.Tables[0].Rows.Count;
            ViewData["totalFinish"] = model.FinishProjectList.Tables[0].Rows.Count;

            return View(model);
        }

        /// <summary>
        /// 新增项目
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CreateProject(FormCollection collection)
        {
            int count= projectManagementRepository.GetModel(r=>r.PROJECT_MANAGEMENT_CREATETIME.Year==DateTime.Now.Year).Count();

            try
            {
                #region 新增项目

                PROJECT_MANAGEMENT model = new PROJECT_MANAGEMENT();
                Guid userId = new Guid(CurrentUser.UserID);
                model.PROJECT_MANAGEMENT_ID = Guid.NewGuid();
                model.PROJECT_MANAGEMENT_TITLE = collection["tb_ProjectName"];
                model.PROJECT_MANAGEMENT_NO ="P"+DateTime.Now.Year+(count+1).ToString().PadLeft(3,'0');
                model.PROJECT_MANAGEMENT_LEADER = collection["tb_ProjectLeader"];
                model.PROJECT_MANAGEMENT_DEADTIME = Convert.ToDateTime(collection["tb_DeadTime"]);
                model.PROJECT_MANAGEMENT_CREATETIME = DateTime.Now;
                model.PROJECT_MANAGEMENT_CONTENT = collection["tb_ProjectDescription"];
                model.PROJECT_MANAGEMENT_BUINESS_CONTACT = collection["tb_BusinessUser"];
                model.PROJECT_MANAGEMENT_STATUS = 0;
                model.PROJECT_MANAGEMENT_BUINESS_DEPARTMENT = collection["tb_BusinessDepartment"];
                model.PROJECT_MANAGEMENT_BUINESS_TYPE = collection["select_BusinessType"];
                model.TEAMSPACE_ID = teamspaceRepository.GetModel(r => r.TEAMSPACE_NAME == CurrentUser.Department).FirstOrDefault().TEAMSPACE_ID;
                model.PROJECT_MANAGEMENT_BUINESS_TEL = collection["tb_BusinessUserTel"];

                projectManagementRepository.Insert(model);

                LoggerFactory.Instance.Logger_Info(CurrentUser.UserName + " " + DateTime.Now + " " + "项目新增成功！");

                #endregion

                #region 添加工作记录

                PROJECT_WORKRECORD modelOfWork = new PROJECT_WORKRECORD();
                modelOfWork.PROJECT_WORKRECORD_TITLE = "项目创建";
                modelOfWork.PROJECT_WORKRECORD_CONTENT = DateTime.Now.Year + "年" + DateTime.Now.Month +
                    "月" + DateTime.Now.Day + "日，" + model.PROJECT_MANAGEMENT_TITLE + "项目分配" + model.PROJECT_MANAGEMENT_LEADER + "负责";
                modelOfWork.LEVEL = 0;
                modelOfWork.PROJECT_MANAGEMENT_ID = model.PROJECT_MANAGEMENT_ID;
                modelOfWork.PROJECT_WORKRECORD_CREATER = userId;
                modelOfWork.PROJECT_WORKRECORD_CREATETIME = DateTime.Now;
                modelOfWork.PROJECT_WORKRECORD_ID = Guid.NewGuid();
                projectWorkReocredRepository.Insert(modelOfWork);

                #endregion

                return this.RedirectToAction("Index", "Project", new { area = "ProjectManageArea", flag = "CreateTrue" });
            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "项目新增失败！ 信息：" + ex.Message);

                return this.RedirectToAction("Index", "Project", new { area = "ProjectManageArea", flag = "CreateFalse", info = ex.Message });
            }



        }

        public ActionResult ProjectInfo(Guid projectId)
        {
            #region 校验身份

            ViewBag.IsAdmin = false;
            string[] pathArr = Request.Path.Split('/');
            try
            {
                Guid userGuid = new Guid(CurrentUser.UserID);
                USER_INFO user = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();
                USER_TEAMSAPCE userTeam = userTeamsapceRepository.GetModel(r => r.USER_ID == user.USER_ID).FirstOrDefault();
                ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == userTeam.ROLE_ID).FirstOrDefault();
                List<MENU_ROLE> menuRole = menuRoleRepository.GetModel(r => r.ROLE_ID == role.ROLE_ID).ToList();
                for (int i = 0; i < menuRole.Count(); i++)
                {
                    int menuId = menuRole[i].MENU_ID;
                    MENU menu = menuRepository.GetModel(r => r.MENU_ID == menuId).FirstOrDefault();
                    if (menu.AREA_NAME == pathArr[2] && menu.CONTROLLER_NAME == pathArr[3])
                    {
                        ViewBag.IsAdmin = true;
                        break;
                    }
                }
            }
            catch (Exception)
            {
                ViewBag.IsAdmin = false;
            }



            #endregion


            PROJECT_MANAGEMENT pro = projectManagementRepository.GetModel(r => r.PROJECT_MANAGEMENT_ID == projectId).FirstOrDefault();

            int monthlyCount = fileRepository.GetModel(
                r => r.FILE_TYPE == "PROJECT_MANAGEMENT_MONTHLY" && r.CONTACT_ID == pro.PROJECT_MANAGEMENT_ID).Count();

            ViewBag.projectId = projectId;

            int workReocredCount = projectWorkReocredRepository.GetModel(r => r.PROJECT_MANAGEMENT_ID == pro.PROJECT_MANAGEMENT_ID).Count();

            ViewBag.MonthlyCount = monthlyCount;
            ViewBag.WorkReocredCount = workReocredCount;

            ProjectManagementInfoViewModel model = new ProjectManagementInfoViewModel();
            model.PROJECT_MANAGEMENT_BUINESS_CONTACT = pro.PROJECT_MANAGEMENT_BUINESS_CONTACT;
            model.PROJECT_MANAGEMENT_BUINESS_TEL = pro.PROJECT_MANAGEMENT_BUINESS_TEL;
            model.PROJECT_MANAGEMENT_CONTENT = pro.PROJECT_MANAGEMENT_CONTENT;
            model.PROJECT_MANAGEMENT_CREATETIME = pro.PROJECT_MANAGEMENT_CREATETIME;
            model.PROJECT_MANAGEMENT_DEADTIME = pro.PROJECT_MANAGEMENT_DEADTIME;
            model.PROJECT_MANAGEMENT_ID = pro.PROJECT_MANAGEMENT_ID;
            model.PROJECT_MANAGEMENT_LEADER = pro.PROJECT_MANAGEMENT_LEADER;
            model.PROJECT_MANAGEMENT_NO = pro.PROJECT_MANAGEMENT_NO;
            model.PROJECT_MANAGEMENT_STATUS = pro.PROJECT_MANAGEMENT_STATUS;
            model.PROJECT_MANAGEMENT_TITLE = pro.PROJECT_MANAGEMENT_TITLE;
            model.PROJECT_MANAGEMENT_BUINESS_DEPARTMENT = pro.PROJECT_MANAGEMENT_BUINESS_DEPARTMENT;
            model.PROJECT_MANAGEMENT_BUINESS_TYPE = pro.PROJECT_MANAGEMENT_BUINESS_TYPE;
            return this.View(model);
        }

        [HttpPost]
        public ActionResult EditProject(FormCollection collection)
        {
            Guid proId = new Guid(collection["hid_ProjectId"]);
            try
            {

                PROJECT_MANAGEMENT model = projectManagementRepository.GetModel(r => r.PROJECT_MANAGEMENT_ID == proId).FirstOrDefault();

                model.PROJECT_MANAGEMENT_BUINESS_CONTACT = collection["tb_BusinessUser"] == "" ? model.PROJECT_MANAGEMENT_BUINESS_CONTACT : collection["tb_BusinessUser"];
                model.PROJECT_MANAGEMENT_BUINESS_TEL = collection["tb_BusinessUserTel"] == "" ? model.PROJECT_MANAGEMENT_BUINESS_TEL : collection["tb_BusinessUserTel"];
                model.PROJECT_MANAGEMENT_CONTENT = collection["tb_DevelopDescription"] == "" ? model.PROJECT_MANAGEMENT_CONTENT : collection["tb_DevelopDescription"];
                model.PROJECT_MANAGEMENT_DEADTIME = collection["tb_DeadTime"] == "" ? model.PROJECT_MANAGEMENT_DEADTIME : Convert.ToDateTime(collection["tb_DeadTime"]);
                model.PROJECT_MANAGEMENT_LEADER = collection["tb_ProjectLeader"] == "" ? model.PROJECT_MANAGEMENT_LEADER : collection["tb_ProjectLeader"];
                model.PROJECT_MANAGEMENT_TITLE = collection["tb_ProjectName"] == "" ? model.PROJECT_MANAGEMENT_TITLE : collection["tb_ProjectName"];
                projectManagementRepository.Update(model);

                LoggerFactory.Instance.Logger_Info(CurrentUser.UserName + " " + DateTime.Now + " " + "项目编辑成功！");

                return this.RedirectToAction("Index", "Project", new { area = "ProjectManageArea", flag = "EditTrue", projectId = proId });

            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "项目编辑失败！ 信息：" + ex.Message);

                return this.RedirectToAction("Index", "Project", new { area = "ProjectManageArea", flag = "EditFalse", info = ex.Message, projectId = proId });
            }
        }

        [HttpPost]
        public ActionResult EditProjectStatus(FormCollection collection)
        {
            Guid proId = new Guid(collection["hid_ProjectId"]);

            try
            {
                PROJECT_MANAGEMENT pro = projectManagementRepository.GetModel(r => r.PROJECT_MANAGEMENT_ID == proId).FirstOrDefault();

                pro.PROJECT_MANAGEMENT_STATUS = Convert.ToInt32(collection["select_ProjectStatus"]);

                projectManagementRepository.Update(pro);

                LoggerFactory.Instance.Logger_Info(CurrentUser.UserName + " " + DateTime.Now + " " + "项目编辑状态成功！");

                return RedirectToAction("Index", "Project", new { area = "ProjectManageArea", flag = "StatusTrue", flagInfo = "项目状态编辑完成！", projectId = proId });

            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "项目编辑状态失败！ 信息：" + ex.Message);

                return RedirectToAction("Index", "Project", new { aarea = "ProjectManageArea", flag = "StatusFalse", info = ex.Message, projectId = proId });
            }
        }

    }
}
